<template>
	<view class="logs-container">
		<!-- Tab 切换 -->
		<view class="tabs-container">
			<view class="tab" :class="{ active: activeTab === 'api' }" @click="activeTab = 'api'">
				接口日志
			</view>
			<view class="tab" :class="{ active: activeTab === 'activities' }" @click="activeTab = 'activities'">
				最近活动
			</view>
		</view>
		<!-- 接口日志相关区域 - 只在选中接口日志时显示 -->
		<view v-if="activeTab === 'api'">
			<!-- 顶部统计卡片区域 -->
			<view class="stats-section">
				<view class="stats-header">
					<text class="section-title">📊 API调用统计</text>
					<button class="clear-btn" @click="onClear">
						<text class="clear-icon">🗑️</text>
						<text>清空日志</text>
					</button>
				</view>
				
				<!-- 圆形统计图表区域 -->
				<view class="charts-container">
					<!-- 成功率圆形进度图 -->
					<view class="chart-item">
						<view class="circle-progress" :style="getCircleProgressStyle()">
							<view class="progress-inner">
								<text class="progress-value">{{ successRate }}%</text>
								<text class="progress-label">成功率</text>
							</view>
						</view>
					</view>
					
					<!-- 总请求数圆形展示 -->
					<view class="chart-item">
						<view class="circle-total">
							<view class="total-inner">
								<text class="total-value">{{ stats.total }}</text>
								<text class="total-label">总请求</text>
							</view>
						</view>
					</view>
					
					<!-- 饼图风格的状态分布 -->
					<view class="chart-item">
						<view class="pie-chart">
							<view class="pie-success" :style="getPieSuccessStyle()"></view>
							<view class="pie-fail" :style="getPieFailStyle()"></view>
							<view class="pie-center">
								<text class="pie-label">状态分布</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 详细统计卡片 -->
				<view class="stats-cards">
					<view class="stat-card success">
						<view class="card-icon">✅</view>
						<view class="card-content">
							<text class="card-value">{{ stats.success }}</text>
							<text class="card-label">成功请求</text>
						</view>
					</view>
					
					<view class="stat-card fail">
						<view class="card-icon">❌</view>
						<view class="card-content">
							<text class="card-value">{{ stats.fail }}</text>
							<text class="card-label">失败请求</text>
						</view>
					</view>
					
					<view class="stat-card info">
						<view class="card-icon">⏱️</view>
						<view class="card-content">
							<text class="card-value">{{ averageTime }}ms</text>
							<text class="card-label">平均耗时</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 筛选器区域 -->
		<view class="filters-section" v-if="activeTab === 'api'">
			<view class="section-title">🔍 筛选条件</view>
			<view class="filters">
				<view class="filter-row">
					<input class="input" v-model="form.keyword" placeholder="🔍 搜索URL或错误信息" />
				</view>
				<view class="filter-row">
					<picker :range="methodOptions" :value="form.methodIndex" @change="onMethodChange">
						<view class="picker">
							<text class="picker-label">请求方法</text>
							<text class="picker-value">{{ methodOptions[form.methodIndex] }}</text>
						</view>
					</picker>
					<picker :range="statusOptions" :value="form.statusIndex" @change="onStatusChange">
						<view class="picker">
							<text class="picker-label">状态码</text>
							<text class="picker-value">{{ statusOptions[form.statusIndex] }}</text>
						</view>
					</picker>
				</view>
				<view class="filter-row">
					<picker :range="successOptions" :value="form.successIndex" @change="onSuccessChange">
						<view class="picker">
							<text class="picker-label">请求结果</text>
							<text class="picker-value">{{ successOptions[form.successIndex] }}</text>
						</view>
					</picker>
					<button class="search-btn" @click="onSearch">
						<text class="search-icon">🔍</text>
						<text>查询</text>
					</button>
				</view>
			</view>
		</view>

		<!-- 接口日志内容 -->
		<view v-if="activeTab === 'api'">
			<!-- 日志列表区域 -->
			<view class="logs-section">
				<view class="section-title">📋 请求日志 ({{ total }}条)</view>
				<view class="list">
					<view v-for="item in list" :key="item.id" class="log-item" @click="toggle(item)">
						<view class="log-header">
							<view class="status-badge" :class="{ success: item.success, fail: !item.success }">
								<text class="status-icon">{{ item.success ? '✅' : '❌' }}</text>
								<text class="status-text">{{ item.success ? 'SUCCESS' : 'FAILED' }}</text>
							</view>
							<view class="method-badge" :class="getMethodClass(item.method)">
								{{ item.method }}
							</view>
							<view class="time-info">
								<text class="duration">{{ item.durationMs }}ms</text>
							</view>
						</view>
						
						<view class="log-content">
							<text class="url">{{ item.url }}</text>
							<view class="log-meta">
								<text class="timestamp">🕐 {{ formatTime(item.timestamp) }}</text>
								<text class="status-code">📊 {{ item.status }}</text>
							</view>
						</view>
						
						<view class="error-info" v-if="!item.success && item.errorMessage">
							<text class="error-icon">⚠️</text>
							<text class="error-message">{{ item.errorMessage }}</text>
						</view>
					</view>
					
					<!-- 空状态 -->
					<view v-if="list.length === 0" class="empty-state">
						<text class="empty-icon">📭</text>
						<text class="empty-text">暂无日志数据</text>
						<text class="empty-desc">API调用日志将在这里显示</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 最近活动内容 -->
		<view v-else-if="activeTab === 'activities'">
			<activity-timeline :activities="recentActivities" scroll-height="600rpx" />
		</view>

		<!-- 分页区域 -->
		<view class="pagination" v-if="total > 0">
			<button class="page-btn" @click="prev" :disabled="page===1">
				<text>⬅️ 上一页</text>
			</button>
			<view class="page-info">
				<text class="page-text">第 {{ page }} 页 / 共 {{ totalPages }} 页</text>
			</view>
			<button class="page-btn" @click="next" :disabled="page >= totalPages">
				<text>下一页 ➡️</text>
			</button>
		</view>
	</view>
</template>

<script>
import { queryLogs, clearLogs, getStats } from '../../utils/api-logger.js'
import ActivityTimeline from '../user/profile/components/ActivityTimeline.vue'
import pointsManager from '../../utils/points-manager.js'

export default {
	components: {
		ActivityTimeline
	},
	data() {
		return {
			activeTab: 'api', // 默认显示接口日志
			recentActivities: [],
			form: {
				keyword: '',
				methodIndex: 0, // ALL
				statusIndex: 0, // ALL
				successIndex: 0 // ALL
			},
			methodOptions: ['ALL','GET','POST','PUT','DELETE'],
			statusOptions: ['ALL','200','201','204','400','401','403','404','409','500','NETWORK_FAIL','LOCAL'],
			successOptions: ['ALL','SUCCESS','FAIL'],
			list: [],
			total: 0,
			page: 1,
			pageSize: 20,
			stats: { total: 0, success: 0, fail: 0 }
		}
	},
	
	computed: {
		// 成功率计算
		successRate() {
			if (this.stats.total === 0) return 0
			return Math.round((this.stats.success / this.stats.total) * 100)
		},
		
		// 平均响应时间
		averageTime() {
			if (this.list.length === 0) return 0
			const totalTime = this.list.reduce((sum, item) => sum + (item.durationMs || 0), 0)
			return Math.round(totalTime / this.list.length)
		},
		
		// 总页数
		totalPages() {
			return Math.ceil(this.total / this.pageSize)
		}
	},
	
	onShow() {
		this.refresh();
		this.loadRecentActivities();
	},
	
	methods: {
		// 加载最近活动记录
		loadRecentActivities() {
			try {
				this.recentActivities = pointsManager.getRecentActivities()
			} catch (error) {
				console.error('加载最近活动失败:', error)
				this.recentActivities = []
			}
		},
		
		buildQuery() {
			const method = this.form.methodIndex === 0 ? '' : this.methodOptions[this.form.methodIndex];
			const status = this.form.statusIndex === 0 ? '' : this.statusOptions[this.form.statusIndex];
			let success;
			if (this.form.successIndex === 1) success = true;
			if (this.form.successIndex === 2) success = false;
			return {
				keyword: this.form.keyword,
				method,
				status,
				success,
				page: this.page,
				pageSize: this.pageSize
			}
		},
		
		refresh() {
			const { total, list } = queryLogs(this.buildQuery());
			this.total = total;
			this.list = list;
			this.stats = getStats();
		},
		
		onSearch() {
			this.page = 1;
			this.refresh();
		},
		
		onMethodChange(e) {
			this.form.methodIndex = Number(e.detail.value);
		},
		
		onStatusChange(e) {
			this.form.statusIndex = Number(e.detail.value);
		},
		
		onSuccessChange(e) {
			this.form.successIndex = Number(e.detail.value);
		},
		
		prev() {
			if (this.page > 1) {
				this.page--;
				this.refresh();
			}
		},
		
		next() {
			if (this.page < this.totalPages) {
				this.page++;
				this.refresh();
			}
		},
		
		onClear() {
			uni.showModal({
				title: '清空日志',
				content: '确定要清空所有日志吗？此操作不可恢复。',
				success: (res) => {
					if (res.confirm) {
						clearLogs();
						this.page = 1;
						this.refresh();
						uni.showToast({
							title: '日志已清空',
							icon: 'success'
						});
					}
				}
			});
		},
		
		toggle(item) {
			// 预留：可展开更多详情
			console.log('点击日志项:', item);
		},
		
		// 获取圆形进度条样式
		getCircleProgressStyle() {
			const percentage = this.successRate;
			const strokeDasharray = 2 * Math.PI * 45; // 圆周长
			const strokeDashoffset = strokeDasharray * (1 - percentage / 100);
			
			return {
				background: `conic-gradient(#4CAF50 0deg ${percentage * 3.6}deg, #f0f0f0 ${percentage * 3.6}deg 360deg)`
			}
		},
		
		// 获取饼图成功部分样式
		getPieSuccessStyle() {
			const percentage = this.successRate;
			return {
				transform: `rotate(${percentage * 3.6}deg)`
			}
		},
		
		// 获取饼图失败部分样式
		getPieFailStyle() {
			const percentage = 100 - this.successRate;
			return {
				transform: `rotate(${this.successRate * 3.6}deg)`
			}
		},
		
		// 获取请求方法样式类
		getMethodClass(method) {
			const classMap = {
				'GET': 'method-get',
				'POST': 'method-post', 
				'PUT': 'method-put',
				'DELETE': 'method-delete'
			}
			return classMap[method] || 'method-default'
		},
		
		// 格式化时间
		formatTime(timestamp) {
			const date = new Date(timestamp);
			return date.toLocaleString('zh-CN', {
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit',
				second: '2-digit'
			});
		}
	}
}
</script>

<style scoped>
.logs-container {
	padding: 20rpx;
	background: #f8f9fa;
	min-height: 100vh;
}

/* Tab 切换样式 */
.tabs-container {
	display: flex;
	background: white;
	border-radius: 16rpx;
	padding: 12rpx;
	margin-bottom: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.tab {
	flex: 1;
	text-align: center;
	padding: 20rpx;
	border-radius: 12rpx;
	font-size: 28rpx;
	font-weight: 500;
	color: #666;
	transition: all 0.3s ease;
}

.tab.active {
	background: linear-gradient(135deg, #667eea, #764ba2);
	color: white;
	box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.tab:active {
	opacity: 0.8;
}

/* 统计区域样式 */
.stats-section {
	margin-bottom: 32rpx;
}

.stats-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.clear-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	background: linear-gradient(135deg, #ff6b6b, #ff5252);
	color: white;
	border: none;
	padding: 16rpx 24rpx;
	border-radius: 25rpx;
	box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
}

.clear-icon {
	font-size: 24rpx;
}

/* 圆形图表容器 */
.charts-container {
	display: flex;
	justify-content: space-around;
	margin-bottom: 32rpx;
	gap: 20rpx;
}

.chart-item {
	flex: 1;
	display: flex;
	justify-content: center;
}

/* 圆形进度图 */
.circle-progress {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.progress-inner {
	width: 120rpx;
	height: 120rpx;
	background: white;
	border-radius: 50%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	box-shadow: inset 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.progress-value {
	font-size: 32rpx;
	font-weight: bold;
	color: #4CAF50;
}

.progress-label {
	font-size: 20rpx;
	color: #666;
	margin-top: 4rpx;
}

/* 总数圆形展示 */
.circle-total {
	width: 160rpx;
	height: 160rpx;
	background: linear-gradient(135deg, #667eea, #764ba2);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

.total-inner {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.total-value {
	font-size: 36rpx;
	font-weight: bold;
	color: white;
}

.total-label {
	font-size: 20rpx;
	color: rgba(255, 255, 255, 0.8);
	margin-top: 4rpx;
}

/* 饼图样式 */
.pie-chart {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	position: relative;
	background: #f44336;
	overflow: hidden;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.pie-success {
	position: absolute;
	width: 50%;
	height: 100%;
	background: #4CAF50;
	transform-origin: right center;
	right: 50%;
}

.pie-fail {
	position: absolute;
	width: 50%;
	height: 100%;
	background: #f44336;
	transform-origin: left center;
	left: 50%;
}

.pie-center {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 80rpx;
	height: 80rpx;
	background: white;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.pie-label {
	font-size: 18rpx;
	color: #666;
	text-align: center;
}

/* 统计卡片 */
.stats-cards {
	display: flex;
	gap: 16rpx;
}

.stat-card {
	flex: 1;
	background: white;
	border-radius: 16rpx;
	padding: 24rpx;
	display: flex;
	align-items: center;
	gap: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.stat-card.success {
	border-left: 6rpx solid #4CAF50;
}

.stat-card.fail {
	border-left: 6rpx solid #f44336;
}

.stat-card.info {
	border-left: 6rpx solid #2196F3;
}

.card-icon {
	font-size: 32rpx;
}

.card-content {
	display: flex;
	flex-direction: column;
}

.card-value {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.card-label {
	font-size: 20rpx;
	color: #666;
	margin-top: 4rpx;
}

/* 筛选器区域 */
.filters-section {
	background: white;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.filters {
	margin-top: 20rpx;
}

.filter-row {
	display: flex;
	gap: 16rpx;
	margin-bottom: 16rpx;
}

.filter-row:last-child {
	margin-bottom: 0;
}

.input {
	flex: 1;
	border: 2rpx solid #e0e0e0;
	border-radius: 12rpx;
	padding: 16rpx;
	font-size: 24rpx;
	background: #fafafa;
}

.input:focus {
	border-color: #667eea;
	background: white;
}

.picker {
	flex: 1;
	border: 2rpx solid #e0e0e0;
	border-radius: 12rpx;
	padding: 16rpx;
	background: #fafafa;
	display: flex;
	flex-direction: column;
}

.picker-label {
	font-size: 20rpx;
	color: #666;
	margin-bottom: 4rpx;
}

.picker-value {
	font-size: 24rpx;
	color: #333;
	font-weight: 500;
}

.search-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	background: linear-gradient(135deg, #667eea, #764ba2);
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 16rpx 24rpx;
	box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.search-icon {
	font-size: 24rpx;
}

/* 日志列表区域 */
.logs-section {
	background: white;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.list {
	margin-top: 20rpx;
}

.log-item {
	background: #fafafa;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 16rpx;
	border-left: 4rpx solid #e0e0e0;
	transition: all 0.3s ease;
}

.log-item:hover {
	background: #f0f0f0;
	transform: translateY(-2rpx);
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.log-item:last-child {
	margin-bottom: 0;
}

.log-header {
	display: flex;
	align-items: center;
	gap: 12rpx;
	margin-bottom: 12rpx;
}

.status-badge {
	display: flex;
	align-items: center;
	gap: 6rpx;
	padding: 8rpx 12rpx;
	border-radius: 20rpx;
	font-size: 20rpx;
	font-weight: 500;
}

.status-badge.success {
	background: rgba(76, 175, 80, 0.1);
	color: #4CAF50;
	border: 1rpx solid rgba(76, 175, 80, 0.3);
}

.status-badge.fail {
	background: rgba(244, 67, 54, 0.1);
	color: #f44336;
	border: 1rpx solid rgba(244, 67, 54, 0.3);
}

.status-icon {
	font-size: 18rpx;
}

.status-text {
	font-size: 18rpx;
}

.method-badge {
	padding: 6rpx 12rpx;
	border-radius: 8rpx;
	font-size: 18rpx;
	font-weight: bold;
	color: white;
}

.method-get {
	background: #4CAF50;
}

.method-post {
	background: #2196F3;
}

.method-put {
	background: #FF9800;
}

.method-delete {
	background: #f44336;
}

.method-default {
	background: #9E9E9E;
}

.time-info {
	margin-left: auto;
}

.duration {
	font-size: 20rpx;
	color: #666;
	background: rgba(0, 0, 0, 0.05);
	padding: 4rpx 8rpx;
	border-radius: 6rpx;
}

.log-content {
	margin-bottom: 12rpx;
}

.url {
	font-size: 24rpx;
	color: #333;
	font-weight: 500;
	margin-bottom: 8rpx;
	word-break: break-all;
}

.log-meta {
	display: flex;
	gap: 16rpx;
}

.timestamp,
.status-code {
	font-size: 20rpx;
	color: #666;
}

.error-info {
	display: flex;
	align-items: flex-start;
	gap: 8rpx;
	background: rgba(244, 67, 54, 0.05);
	padding: 12rpx;
	border-radius: 8rpx;
	border-left: 3rpx solid #f44336;
}

.error-icon {
	font-size: 20rpx;
	margin-top: 2rpx;
}

.error-message {
	flex: 1;
	font-size: 20rpx;
	color: #f44336;
	word-break: break-all;
}

/* 空状态 */
.empty-state {
	text-align: center;
	padding: 80rpx 40rpx;
}

.empty-icon {
	font-size: 80rpx;
	margin-bottom: 20rpx;
}

.empty-text {
	display: block;
	font-size: 28rpx;
	color: #666;
	margin-bottom: 12rpx;
}

.empty-desc {
	display: block;
	font-size: 22rpx;
	color: #999;
}

/* 分页区域 */
.pagination {
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: white;
	border-radius: 16rpx;
	padding: 24rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.page-btn {
	background: linear-gradient(135deg, #667eea, #764ba2);
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 16rpx 24rpx;
	font-size: 24rpx;
	box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.page-btn:disabled {
	background: #e0e0e0;
	color: #999;
	box-shadow: none;
}

.page-info {
	flex: 1;
	text-align: center;
}

.page-text {
	font-size: 24rpx;
	color: #666;
}
</style>